package it.polimi.swim.session;

import it.polimi.swim.entity.HelpRequest;
import it.polimi.swim.entity.Skill;
import it.polimi.swim.entity.SystemUser;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;


@Stateless
@RemoteBinding(jndiBinding = HelpRequestManagerBean.REMOTE)
public class HelpRequestManagerBean implements HelpRequestManagerBeanRemote {
	
	
	public static final String REMOTE = "HelpRequestManagerBean/remote";
	
	@PersistenceContext(unitName = "SWIMv2")
	private EntityManager em;
	

    public HelpRequestManagerBean() {
        
    }

	@SuppressWarnings("unchecked")
	@Override
	public HelpRequest createHelpRequest(String title, String description, Skill skill,int idCreator) {
		
		HelpRequest helpRequest=new HelpRequest();
		//recuperare info user e metterle in oggetto user da passare a setCreator
		//helpRequest.setCreator(creator);
		Query q = null;
		q = em.createNamedQuery("SystemUser.getUserById");
		q.setParameter("id", idCreator);
		SystemUser creator = (SystemUser) q.getSingleResult();
		System.out.println(creator.getMail());
		helpRequest.setTitle(title);
		helpRequest.setIdCreator(creator);
		helpRequest.setDescription(description);
		helpRequest.setNecessarySkill(skill);
		helpRequest.setStatus(false);
		em.persist(helpRequest);
		System.out.println("creata help");
		return helpRequest;
	}

	@Override
	public HelpRequest getHelpRequestById(int idHelp) {
		
		Query q = em.createNamedQuery("HelpRequest.getHelpRequestById");
		q.setParameter("id", idHelp);
		HelpRequest help = (HelpRequest) q.getSingleResult();
		return help;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setHelpReceiver(HelpRequest hr, SystemUser user) {
		Query q = em.createNamedQuery("HelpRequest.getNewHelpRequestById");
		q.setParameter("id", hr.getId());
		HelpRequest help = (HelpRequest) q.getSingleResult();
		
		q = em.createNamedQuery("SystemUser.getUserById");
		q.setParameter("id", user.getId());
		SystemUser u = (SystemUser) q.getSingleResult();
		
		help.setReceiver(u);
		user.getOtherHelp().add(help);
		em.persist(help);
		em.persist(u);
	}

	@Override
	public void deleteHelp(int idHelp) {
		Query q = em.createNamedQuery("HelpRequest.getNewHelpRequestById");
		q.setParameter("id", idHelp);
		HelpRequest help = (HelpRequest) q.getSingleResult();
		help.getIdCreator().getCreator().remove(help);
		help.getReceiver().getOtherHelp().remove(help);
		q = em.createNamedQuery("HelpRequest.DeteleHelpRequest");
		q.setParameter("id", idHelp);
		q.executeUpdate();		
	}

	@Override
	public void confirmHelp(int idHelp) {
		Query q = em.createNamedQuery("HelpRequest.getNewHelpRequestById");
		q.setParameter("id", idHelp);
		HelpRequest help = (HelpRequest) q.getSingleResult();
		help.setStatus(true);
		em.persist(help);
		
	}

}
